import router from "@/router";
import axios from "axios";

const request =axios.create({
    baseURL:'http://localhost:9090',  //后端接口地址
    timeout:30000                     //响应时间
})

request.interceptors.request.use( config=>{
    config.headers['Content-Type'] ='application/json;charset=utf-8';
    let user = JSON.parse(localStorage.getItem("honey-user")||'{}')
    config.headers['token'] = user.token
    return config
}, error =>{
    console.error('request error: ' + error)
    return Promise.reject(error)
});
//response 拦截器
//可以在接口响应后统一处理结果
request.interceptors.response.use(
    respone =>{
        let res=respone.data;

        //兼容服务端返回的字符串数据
        if(typeof res === 'string'){
            res = res? JSON.parse(res):res
        }
        if(res.code==='401'){
            router.push('/login')
        }
        return res;
    },
    error => {
        console.error('response error：' + error)
        return Promise.reject(error)
    }
)


export default request